<?php
/**
 * ROLE
 * @author NguyenNT
 * Description:
 */
class RoleController extends Zend_Controller_Action
{
    private $_error = array();
    private $_paginator = array('itemCountPerPage' => 40, 'pageRange' => 3);
    private $_arrParam;

    public function init ()
    {
        $auth = Zend_Auth::getInstance();
        if ($auth->hasIdentity()) {
            $userInfo = $auth->getIdentity();
            Zend_Layout::getMvcInstance()->assign('username', $userInfo['username']);
            $this->_arrParam = $this->_request->getParams();
            $this->_paginator['currentPage'] = $this->_getParam('page',1);
            $this->view->actionMain = $this->_arrParam['module'] . '/' . $this->_arrParam['controller'] . '/' . $this->_arrParam['action'];
        } else {
            return $this->_helper->redirector('index', 'Auth');
        }
    }

    public function indexAction()
    {
        $acl = new My_Acl();
        if(!$acl->isAllowed(Zend_Auth::getInstance()->getIdentity(), $this->_request)){
            $this->_redirect('error/accessdenied');
        }

        $this->view->actionDelete = 'role/delete';
        $this->view->actionAdd = 'role/add';
        $this->view->actionEdit = 'role/edit';
        $roleModel = new Model_Roles();
        $paginator = new My_Paginator();
        $paginator = $paginator->createPaginator($roleModel->countItems(),
                                        $this->_paginator['itemCountPerPage'],
                                        $this->_paginator['pageRange'],
                                        $this->_paginator['currentPage']);
        $this->view->paginator = $paginator;
        $limit = array('offset' => ($this->_paginator['currentPage']-1) * $this->_paginator['itemCountPerPage'],
                                'count' => $this->_paginator['itemCountPerPage']);
        $this->view->roles = $roleModel->getItems($limit);
        $this->view->message = current($this->_helper->flashMessenger->getMessages());
    }

    public function addAction()
    {
        $acl = new My_Acl();
        if(!$acl->isAllowed(Zend_Auth::getInstance()->getIdentity(), $this->_request)){
            $this->_redirect('error/accessdenied');
        }

    	$roleModel = new Model_Roles();
        if ($this->getRequest()->isPost() && $this->_validateForm())
        {
            $info = $this->getRequest()->getPost();
            $data = array ( 'roleName' => $info['roleName']);
            $roleId = $roleModel->insert($data);
            //Update role
            $privilegeModel = new Model_Privilege();
            foreach ($info['projects'] as $p) {
                foreach ($info['resources'] as $r) {
                    $views = '';
                    if(isset($info["views_{$r}"][0])){
                        $views = explode('-', $info["views_{$r}"]);
                        $views = json_encode($views);
                    }
                    $privilege[] = array('roleId' => $roleId,
                                        'projectId' => $p,
                                        'resourceId' => $r,
                                        'views' => $views);

                }
            }
            $privilegeModel->insertItems($privilege);
            $this->_helper->flashMessenger('Insert is success !!!');
            $this->_redirect('role/index');
        }
        $this->view->error = $this->_error;
        $this->_getForm();
    }

    public function deleteAction()
    {
        $acl = new My_Acl();
        if(!$acl->isAllowed(Zend_Auth::getInstance()->getIdentity(), $this->_request)){
            $this->_redirect('error/accessdenied');
        }

    	$this->_helper->layout()->disableLayout();
    	$this->_helper->viewRenderer->setNoRender();
    	if($this->getRequest()->isPost() && $this->_getParam('selected') !== NULL &&  $this->_validateDelete())
    	{
            $roleModel = new Model_Roles();
            $userModel = new Model_Users();
            $privilegeModel = new Model_Privilege();
            foreach ($this->_getParam('selected') as $id)
            {
                $userModel->deleteUsersRolesByRoleId($id);
                $privilegeModel->delete('roleId = ' . $id . ' AND roleId <> 1');
                $roleModel->deleteItem($id);
            }
            $this->_helper->flashMessenger('Delete is success!!!');
            $this->_redirect('role');
        }
    }

    public function editAction()
    {

        $acl = new My_Acl();
        if(!$acl->isAllowed(Zend_Auth::getInstance()->getIdentity(), $this->_request)){
            $this->_redirect('error/accessdenied');
        }

    	$roleModel = new Model_Roles();
        if ($this->getRequest()->isPost() && $this->_validateForm())
        {

            $info = $this->getRequest()->getPost();
            $roleId = $info['itemId'];
            $data = array ( 'roleName' => $info['roleName']);
            $roleModel->updateItem($roleId,$data);
            //Update role
            $privilegeModel = new Model_Privilege();
            $privilegeModel->delete('roleId = ' . $roleId);
            foreach ($info['projects'] as $p) {
                foreach ($info['resources'] as $r) {
                    $views = '';
                    if(isset($info["views_{$r}"][0])){
                        $views = explode('-', $info["views_{$r}"]);
                        $views = json_encode($views);
                    }
                    $privilege[] = array('roleId' => $roleId,
                                        'projectId' => $p,
                                        'resourceId' => $r,
                                        'views' => $views);

                }
            }

            $privilegeModel->insertItems($privilege);
            $this->_helper->flashMessenger('Update is success !!!');
            $this->_redirect('role/index');
        }
        $this->view->error = $this->_error;
        $this->_getForm();
        $this->_helper->viewRenderer('add');
    }

    private function _getForm()
    {
    	$roleModel = new Model_Roles();
    	if ($this->getRequest()->isPost()){
            $info = $this->getRequest()->getPost();
    	}

    	if ($this->_getParam('itemId') !== null && $this->_arrParam['action'] == 'edit'){
            $itemId = $this->_getParam('itemId');
            $info = $roleModel->getItem($itemId);
            $this->view->itemId = $itemId;
    	}

    	//Button Action
    	$this->view->actionCancel = 'role';
    	$data = array();
        //Role Name
    	if(isset($info['roleName']))
            $data['roleName'] = $info['roleName'];
    	else
            $data['roleName'] = '';

        //Projects
        if(isset($info['projects']))
            $data['projects'] = $info['projects'];
    	else
            $data['projects'] = array();

    	//Privilege
        if(isset($info['resources']))
            $data['resources'] = $info['resources'];
    	else
            $data['resources'] = array();

        //Get All Project
        $projectModel = new Model_Project();
        $this->view->projects = $projectModel->getItems();
        //Get All Resource
        $resourceModel = new Model_Resource();
        $resources = $resourceModel->getItems()->toArray();

        $this->view->resources = $resources;
    	$this->view->info = $data;


    }

    /**
     * @todo Hiện lên trang để thiết lập quyền view cho role
     */
    public function viewsdetailAction()
    {
        Zend_Layout::getMvcInstance()->disableLayout();
        $resourceId = $this->_getParam('resourceId',0);
        $views = $this->_getParam('views','');
        $viewConfig = new Zend_Config_Ini(CONFIG_PATH . '/columns.ini', APPLICATION_ENV);
        $this->view->resourceId = $resourceId;
        $this->view->viewsConfig = $viewConfig->views;
        $this->view->views = explode('-', $views);
    }

    private function _validateForm()
    {

    	return TRUE;
    }

    private function _validateDelete()
    {
    	/*Check Permission*/
    	return TRUE;
    }

}







